package com.szsh.aiot.hsm.service.impl;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.szsh.aiot.common.core.domain.AjaxResult;
import com.szsh.aiot.common.core.domain.Key;
import com.szsh.aiot.common.core.domain.RequestDto;
import com.szsh.aiot.common.utils.StringUtils;
import com.szsh.aiot.framework.aspectj.CustomPermissionAspect;
import com.szsh.aiot.framework.constant.Constants;
import com.szsh.aiot.hsm.dao.WapLoginDao;
import com.szsh.aiot.hsm.properties.WapLoginProperties;
import com.szsh.aiot.hsm.service.WapLoginService;
import com.szsh.aiot.common.utils.XXTea;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;

@Service
public class WapLoginServiceImpl implements WapLoginService {
    private static final Logger LOGGER = LoggerFactory.getLogger(WapLoginServiceImpl.class);

    private final WapLoginDao wapLoginDao;

    private final WapLoginProperties wapLoginProperties;

//    private final StringRedisTemplate stringRedisTemplate;

    private final HashOperations<String, String, String> stringHashOperations;

    private final Gson gson;

    private final CustomPermissionAspect customPermissionAspect;

    public WapLoginServiceImpl(WapLoginDao wapLoginDao, WapLoginProperties wapLoginProperties, StringRedisTemplate stringRedisTemplate, Gson gson, CustomPermissionAspect customPermissionAspect) {
        this.wapLoginDao = wapLoginDao;
        this.wapLoginProperties = wapLoginProperties;
        this.stringHashOperations = stringRedisTemplate.opsForHash();
        this.gson = gson;
        this.customPermissionAspect = customPermissionAspect;
    }

    @Override
    public AjaxResult getLoginUrl(RequestDto requestDto) {
        // 获取参数
        String returnUrl = requestDto.getRequestJsonElement().getAsJsonObject().get("returnUrl").getAsString();
        String wapLoginUrl = wapLoginDao.getLoginUrl(returnUrl, requestDto.getAppId(), requestDto.getVersion());
        if (StringUtils.isBlank(wapLoginUrl)) {
            return AjaxResult.error("生成登录地址失败");
        } else {
            JsonObject returnJsonObject = new JsonObject();
            returnJsonObject.addProperty("wapLoginUrl", wapLoginUrl);
            return AjaxResult.success(returnJsonObject);
        }
    }

    @Override
    public AjaxResult getLogOutUrl(RequestDto requestDto) {
        // 获取参数
        String returnUrl = requestDto.getRequestJsonElement().getAsJsonObject().get("returnUrl").getAsString();
        String wapLogOutUrl = wapLoginDao.getLogOutUrl(returnUrl);
        if (StringUtils.isBlank(wapLogOutUrl)) {
            return AjaxResult.error("生成登录地址失败");
        } else {
            JsonObject returnJsonObject = new JsonObject();
            returnJsonObject.addProperty("wapLogOutUrl", wapLogOutUrl);
            return AjaxResult.success(returnJsonObject);
        }
    }

    @Override
    public String getPhoneNumber(String paras) {
        // 密文解密
        String decryptParas;
        try {
            decryptParas = XXTea.decrypt(paras, wapLoginProperties.getAppSecret());
        } catch (Exception e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("天翼账号平台返回解密失败", e);
            }
            return null;
        }
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("天翼账号平台返回明文[{}]", decryptParas);
        }
        if (StringUtils.isBlank(decryptParas)) {
            return "";
        }
        // 解析参数
        MultiValueMap<String, String> multiValueMap = UriComponentsBuilder.newInstance().query(decryptParas).build()
                .getQueryParams();

        // 0:正常
        String result = multiValueMap.getFirst("result");
        if ("0".equals(result)) {
            // 获取 code
            String code = multiValueMap.getFirst("code");
            if (StringUtils.isNotBlank(code)) {
                // 根据code获取手机号码
                // 获取手机号码
                return wapLoginDao.getPhoneNumber(code);
            }
        }
        return null;
    }

    @Override
    public AjaxResult encryptPhoneNumber(String phoneNumber, String appId, String version) {
        try {
            // 根据 appId 和 version 获取密钥
            String keyStr = stringHashOperations.get(Constants.REDIS_KEY_PREFIX + appId, version);

            if (StringUtils.isBlank(keyStr)) {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("[根据appId和version获取密钥失败]");
                }
            }
            // 将 keysStr 转换成 key对象
            Key key = gson.fromJson(keyStr, Key.class);
            if (null == key) {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("[根据appId和version获取密钥转换失败]");
                }
                return AjaxResult.error("查找密钥失败");
            } else {
                // 处理结果
                return customPermissionAspect.handleAjaxResult(AjaxResult.success("成功", phoneNumber), key);
            }
        } catch (Exception e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("[根据appId和version获取密钥解密失败]", e);
            }
            return AjaxResult.error("系统异常");
        }
    }
}
